﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Ayatta.Contract.Domain
{
    [Serializable]
    public abstract class Validatable<T> : IEntity<T>, IValidatableObject
    {
        public T Id { get; set; }

        protected virtual FluentValidation.Results.ValidationResult Validate()
        {
            return null;
        }

        public IDictionary<string, string> GetErrorMessage()
        {
            var result = GetErrorMessages();
            return result.ToDictionary(o => o.Key, o => o.Value.FirstOrDefault());
        }

        public IDictionary<string, List<string>> GetErrorMessages()
        {
            var result = Validate();
            var dic = new Dictionary<string, List<string>>();
            if (!result.IsValid)
            {
                var temp = result.Errors.Select(o => new { o.PropertyName, o.ErrorMessage }).GroupBy(o => o.PropertyName);
                foreach (var o in temp)
                {
                    dic.Add(o.Key, o.Select(e => e.ErrorMessage).ToList());
                }
            }
            return dic;
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = Validate() ?? new FluentValidation.Results.ValidationResult();

            return result.Errors.Select(o => new ValidationResult(o.ErrorMessage, new[] { o.PropertyName }));
        }

    }
}